package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     * @param dto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //1.校验老人是否已入住
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus,1)
        );
        if (ObjectUtil.isNotEmpty( elder)) {
            throw new RuntimeException("该老人已入住");
        }
//从此步开始老人没有入住
        //2.更新床位为已入住状态
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.新增或更新老人
        elder = saveOrUpdateElder(dto, bed);

        //4.签约办理新增
        insertContract(dto,elder);
        //5.新增入住信息
        Long checkInId = saveCheckIn(dto, elder);
        //6.新增入住配置信息
        insertCheckInConfig(dto,checkInId);
    }

    /**
     * 入住配置信息新增
     * @param dto
     */
    private void insertCheckInConfig(CheckInApplyDto dto,Long checkInId) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 入住信息新增
     * @param dto
     */
    private Long saveCheckIn(CheckInApplyDto dto,Elder elder) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckIn checkIn = BeanUtil.toBean(checkInConfigDto, CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn.getId();
    }

    /**
     * 新增合同
     * @param dto
     */
    private void insertContract(CheckInApplyDto dto,Elder elder) {
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderId(Integer.parseInt(elder.getId()+""));
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);

        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人
     * @param dto
     */
    private Elder saveOrUpdateElder(CheckInApplyDto dto, Bed bed) {
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder newElder = BeanUtil.toBean(checkInElderDto, Elder.class);
        newElder.setStatus(1);
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());

        //去根据身份证号查询老人，并且状态不等于1，如果不等于空，则表示更新，否则新增
        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .ne(Elder::getStatus,1)
        );
        if (ObjectUtil.isNotEmpty(oldElder)) {
            //执行更新
            elderMapper.updateById(newElder);
        }else{
            //执行新增
            elderMapper.insert(newElder);
        }
        return newElder;

    }
}
